package aom.ju.ss.view.base;

import static android.widget.ImageView.ScaleType.FIT_CENTER;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import androidx.appcompat.widget.AppCompatImageView;

import aom.ju.ss.R;


/**
 *
 */
public class SwitchButton extends AppCompatImageView implements OnTouchListener {

    private boolean isChoose = false;// 记录当前按钮是否打开,true为打开,flase为关闭


    private OnChangedListener onChangedListener;


    public SwitchButton(Context context) {
        super(context);
        init();
    }

    public SwitchButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SwitchButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {// 初始化
        setOnTouchListener(this);// 设置监听器,也可以直接复写OnTouchEvent
    }

    @Override
    protected void onDraw(Canvas canvas) {// 绘图函数
        super.onDraw(canvas);

        setScaleType(FIT_CENTER );
        if (isChoose) {
//            setBackgroundResource(R.drawable.nim_slide_toggle_on);
            setImageResource(R.drawable.nim_slide_toggle_on);
        } else {
//            setBackgroundResource(R.drawable.nim_slide_toggle_off);
            setImageResource(R.drawable.nim_slide_toggle_off);
        }
    }

    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {// 松开
            isChoose = !isChoose;
            if (onChangedListener != null) {
                onChangedListener.OnChanged(v, isChoose);
            }
            invalidate();// 重画控件
        }


        return true;
    }

    public void setOnChangedListener(OnChangedListener listener) {// 设置监听器,当状态修改的时候
        onChangedListener = listener;
    }

    public interface OnChangedListener {

        void OnChanged(View v, boolean checkState);
    }

    public void setCheck(boolean isChecked) {
        isChoose = isChecked;
        invalidate();
    }

    public boolean isChoose() {
        return this.isChoose;
    }


}
